//
//  AssetView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/5/4.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class AssetView: BaseView, UITableViewDataSource, UITableViewDelegate, UICollectionViewDelegate,
UICollectionViewDataSource, AssetCollecCellDelegate, UIScrollViewDelegate {
    var viewModel:AssetViewModel?
    var isHiddenCoin:Bool = false //是否隐藏0
    var selectIndex = 1
    lazy var tableView:UITableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.grouped)
    lazy var headView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 230))
        view.themeBackground = ThemeManager.ThemeColorKeys.background
        return view
    }()
    
    init(dataSource: BaseViewModel?,selectIndex: Int = 1) {
        self.selectIndex = selectIndex
        super.init(dataSource: dataSource)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var collectionView: UICollectionView = {
        let layout = AssetLayout()
        layout.selectIndex = selectIndex
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.decelerationRate = UIScrollViewDecelerationRateFast
        collectionView.dataSource = self
        collectionView.themeBackground = ThemeManager.ThemeColorKeys.background
        collectionView.register(AssetViewCell.self, forCellWithReuseIdentifier: "identifier")
        self.addSubview(collectionView)
        return collectionView
    }()
    
    lazy var coninNameLabel: UILabel = {
        let label = BaseLabel(style: .thirdStyle)
        label.text = kText("币种")
        label.font = UIFont.systemFont(ofSize: 12)
        return label
    }()
//    lazy var describLabel: UILabel = {
//        let label = BaseLabel(style: .twiceStyle)
//        label.font = UIFont.systemFont(ofSize: 12)
//        label.text = "隐藏资产为0币种"
//        return label
//    }()
    
    lazy var hiddenCoinBtn: CustomBtn = {
       let btn = CustomBtn()
       btn.photoImageView.image = UIImage(named: "assetUnSelect")
       btn.nameLabel.text = kText("隐藏资产为0币种")
       btn.nameLabel.font = UIFont.systemFont(ofSize: 12)
       btn.nameLabel.themeTextColor = ThemeManager.ThemeColorKeys.text2
       btn.addTarget(self, action: #selector(hiddenCoinBtnAction), for: UIControlEvents.touchUpInside)
       return btn
    }()
    

    override func setUpUI() -> Void {
        self.viewModel = dataSource as? AssetViewModel
        self.dataSource = dataSource
        self.themeBackground = ThemeManager.ThemeColorKeys.background
        //注册监听
        self.viewModel?.addObserver(self, forKeyPath: "refreshBool", options: [.new,.old], context: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(changeStates), name: NSNotification.Name.Exchange.assetDidChange, object: nil)
        
        tableView.tableHeaderView = headView
        self.addSubview(tableView)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        tableView.themeBackground = ThemeManager.ThemeColorKeys.background
        tableView.delegate = self
        tableView.dataSource = self
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.top.equalToSuperview()
        }
        
        headView.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(3.5)
            make.left.right.equalToSuperview()
            make.height.equalTo(163)
        }
        
        headView.addSubview(coninNameLabel)
        coninNameLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.bottom.equalToSuperview().offset(-10)
        }
        
//        headView.addSubview(describLabel)
//        describLabel.snp.makeConstraints { (make) in
//            make.right.equalToSuperview().offset(-15)
//            make.bottom.equalToSuperview().offset(-10)
//        }
        
        headView.addSubview(hiddenCoinBtn)
        hiddenCoinBtn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(0)
            make.bottom.equalToSuperview().offset(0)
            make.height.equalTo(60)
            make.width.equalTo(250)
        }
        hiddenCoinBtn.nameLabel.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-10)
            make.right.equalToSuperview().offset(-15)
        }
        hiddenCoinBtn.photoImageView.snp.makeConstraints { (make) in
            make.right.equalTo(hiddenCoinBtn.nameLabel.snp.left).offset(-5)
            make.centerY.equalTo(hiddenCoinBtn.nameLabel)
        }
        
        let lineView = UIView()
        lineView.themeBackground = ThemeManager.ThemeColorKeys.tabLineColor
        headView.addSubview(lineView)
        lineView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(0.5)
        }
    }
    
    
    //MARK tableViewDelegate
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if selectIndex == 0 {
            return isHiddenCoin ? APPAssetInfo.default.haveLegalArr.count : APPAssetInfo.default.legalAssetArr.count
        }else if selectIndex == 1 {
            return isHiddenCoin ? APPAssetInfo.default.haveCoinArr.count : APPAssetInfo.default.coinAssetArr.count
        }else {
            return isHiddenCoin ? APPAssetInfo.default.haveLeverArr.count : APPAssetInfo.default.leverAssetArr.count
        }
   
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identy = "identyCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: identy) as? AssetTableViewCell
        if cell == nil {
            cell = AssetTableViewCell(style: .default, reuseIdentifier: identy)
            cell?.selectionStyle = .none
        }
        if selectIndex == 0 {
            cell?.setModel(model: isHiddenCoin ?  APPAssetInfo.default.haveLegalArr[indexPath.row] : APPAssetInfo.default.legalAssetArr[indexPath.row])
        }else if selectIndex == 1 {
            cell?.setModel(model: isHiddenCoin ? APPAssetInfo.default.haveCoinArr[indexPath.row]  : APPAssetInfo.default.coinAssetArr[indexPath.row])
        }else {
             cell?.setModel(model: isHiddenCoin ? APPAssetInfo.default.haveLeverArr[indexPath.row]  : APPAssetInfo.default.leverAssetArr[indexPath.row])
        }
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 81.5
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let controller = CoinTransViewController()
        controller.viewModel?.selectIndex = indexPath.row
        if selectIndex == 0 {
            if isHiddenCoin {
                controller.viewModel?.model = APPAssetInfo.default.haveLegalArr[indexPath.row]
            }else {
                controller.viewModel?.model = APPAssetInfo.default.legalAssetArr[indexPath.row]
            }
            controller.viewModel?.type = .legalType
        }else if selectIndex == 1 {
//            controller.viewModel?.coinArr = (viewModel?.dateArr)!
            if isHiddenCoin {
                controller.viewModel?.model = APPAssetInfo.default.haveCoinArr[indexPath.row]
            }else {
                controller.viewModel?.model = APPAssetInfo.default.coinAssetArr[indexPath.row]
            }
            controller.viewModel?.type = .coinType
            
        }else {

            if isHiddenCoin {
                controller.viewModel?.model = APPAssetInfo.default.haveLeverArr[indexPath.row]
            }else {
                controller.viewModel?.model = APPAssetInfo.default.leverAssetArr[indexPath.row]
            }
            controller.viewModel?.type = .leverType
        }

        self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 2
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:AssetViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier", for: indexPath) as! AssetViewCell
        cell.contentView.layer.cornerRadius = 2.5;
        cell.delegate = self
        if indexPath.row == 0 {
            cell.imageView.image = UIImage(named: "assetBlue")
            cell.moneyLabel.textColor = UIColor(hexStr: "#97a5d9")
            cell.horiLine.backgroundColor = UIColor(hexStr: "#2557d7")
            cell.verLine.backgroundColor = UIColor(hexStr: "#5f6bc2")
            cell.sendBtn.photoImageView.image = UIImage(named: "assetOut")
            cell.receiveBtn.photoImageView.image = UIImage(named: "assetIn")
            cell.kindLabel.text = String(format: "%@ %@ BTC", kText("估值"),APPAssetInfo.default.totalLevBtc)
            cell.moneyLabel.text = String(format: "%@ %@", APPAssetInfo.default.totalLevCoin,AppCacheInfo.default.currency)
            cell.sendBtn.nameLabel.text = kText("划出")
            cell.receiveBtn.nameLabel.text = kText("划入")
            cell.nameLabel.text = kText("法币交易账户")
        }else if indexPath.row == 1 {
            cell.imageView.image = UIImage(named: "assetViolet")
            cell.moneyLabel.textColor = UIColor(hexStr: "#be97d9")
            cell.kindLabel.text = String(format: "%@ %@ BTC", kText("估值"),APPAssetInfo.default.totalBtc)
            cell.moneyLabel.text = String(format: "%@ %@", APPAssetInfo.default.totalCoin,AppCacheInfo.default.currency)
            cell.horiLine.backgroundColor = UIColor(hexStr: "#8b41bd")
            cell.verLine.backgroundColor = UIColor(hexStr: "#9a5fc2")
            cell.receiveBtn.photoImageView.image = UIImage(named: "assetReceive")
            cell.sendBtn.photoImageView.image = UIImage(named: "assetSend")
            cell.sendBtn.nameLabel.text = kText("发送")
            cell.receiveBtn.nameLabel.text = kText("接收")
            cell.nameLabel.text = kText("币币交易账户")
        }else {
            cell.imageView.image = UIImage(named: "assetYellow")
            cell.moneyLabel.textColor = UIColor(hexStr: "#d9c997")
            cell.horiLine.backgroundColor = UIColor(hexStr: "#d5b91b")
            cell.verLine.backgroundColor = UIColor(hexStr: "#d2b85c")
            cell.sendBtn.nameLabel.text = kText("划出")
            cell.receiveBtn.nameLabel.text = kText("划入")
            cell.sendBtn.photoImageView.image = UIImage(named: "assetOut")
            cell.receiveBtn.photoImageView.image = UIImage(named: "assetIn")
            cell.nameLabel.text = kText("杠杆交易账户")
            cell.kindLabel.text = String(format: "%@ %@ BTC", kText("估值"),APPAssetInfo.default.totalVerBtc)
            cell.moneyLabel.text = String(format: "%@ %@",APPAssetInfo.default.totalVerCoin,AppCacheInfo.default.currency)
        }

        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.contentOffset = CGPoint(x:  indexPath.row * Int(kSCREEN_WIDTH-41), y: 0)
        selectIndex = indexPath.row
        tableView.reloadData()
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView == collectionView {
            
        }
    }
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if scrollView.isEqual(collectionView) {
            if 0 == Int(scrollView.contentOffset.x/(kSCREEN_WIDTH-46)) {
                if selectIndex == 0 {
                    return
                }
                selectIndex = 0
                tableView.reloadData()
            }else if 1 == Int(scrollView.contentOffset.x/(kSCREEN_WIDTH-46)) {
                if selectIndex == 1 {
                    return
                }
                selectIndex = 1
                tableView.reloadData()
            }else if 2 == Int(scrollView.contentOffset.x/(kSCREEN_WIDTH-46)) {
                if selectIndex == 2 {
                    return
                }
                selectIndex = 2
                tableView.reloadData()
            }
        }
        
    }
    
    /// KVO监听属性
    ///
    /// - Parameters:
    ///   - keyPath: 被监听的属性名
    ///   - object:
    ///   - change:
    ///   - context:
    @objc override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "refreshBool" {
            tableView.reloadData()
            collectionView.reloadData()
        }
        
    }
    
    @objc func changeStates() {
        self.viewModel?.needRefreshCoinKind = false
        APPAssetInfo.default.archiveAll(self,block: {() in
            self.viewModel?.refreshBool = true
        })
    }
    
    
    //MARK AssetCollecCellDelegate
    func sendCoin() {
        if !AppSecurityInfo.default.model.isTradePwd {
            CYMBShow.showMessage(kText("请先设置交易密码"))
            return
        }
        if selectIndex == 0 {
            if APPAssetInfo.default.leverKindArray.count == 0 {
                CYMBShow.showMessage(kText("当前无法进行划出操作"))
                return
            }
            if !(APPAssetInfo.default.chekSupport()) {
                CYMBShow.showMessage(kText("去向账户无币种"))
                return
            }
            let controller = TransferViewController()
            controller.viewModel?.sendCoin = .legalType
            controller.viewModel?.receiveCoin = .coinType
            self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
        }else if selectIndex == 1 {
            if APPAssetInfo.default.haveCoinArr.count == 0 {
                CYMBShow.showMessage(kText("币币账户资金不足,请充值"))
                return
            }
            if APPAssetInfo.default.coninKidArray.count == 0 {
               CYMBShow.showMessage(kText("当前无法提现"))
                return
            }
            
        let controller = SendCoinViewController()
        self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
        }else {
            if APPAssetInfo.default.coninKidArray.count == 0 {
                CYMBShow.showMessage(kText("当前无法进行划出操作"))
                return
            }
            let controller = TransferViewController()
            controller.viewModel?.sendCoin = .leverType
            controller.viewModel?.receiveCoin = .coinType
            self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
        }
    }
    func receive()  {
        if !AppSecurityInfo.default.model.isTradePwd && selectIndex != 1{
            CYMBShow.showMessage(kText("请先设置交易密码"))
            return
        }
        if selectIndex == 0 {
            if APPAssetInfo.default.leverKindArray.count == 0 {
                CYMBShow.showMessage(kText("当前无法进行划入操作"))
                return
            }
            if !(APPAssetInfo.default.chekSupport()) {
                CYMBShow.showMessage(kText("来源账户无币种"))
                return
            }
            let controller = TransferViewController()
            controller.viewModel?.sendCoin = .coinType
            controller.viewModel?.receiveCoin = .legalType
            self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
        }else if selectIndex == 1 {
            if APPAssetInfo.default.coninKidArray.count == 0 {
                CYMBShow.showMessage(kText("当前无法充值"))
                return
            }
        
            var canUseArr:[TradeCoinModel] = []
            for model  in (APPAssetInfo.default.coninKidArray) {
                let useNumber = model.isrecharge ?? 0
                if useNumber != 0 {
                    canUseArr.append(model)
                }
            }
 
        let controller = ReceiveCoinViewController()
        controller.viewModel?.coninKidArray = canUseArr
        self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
            
        }else {
            if APPAssetInfo.default.coninKidArray.count == 0 {
                CYMBShow.showMessage("当前无法进行划入操作")
                return
            }
            let controller = TransferViewController()
            controller.viewModel?.receiveCoin = .leverType
            controller.viewModel?.sendCoin = .coinType
            self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
        }
    }
    
    @objc func hiddenCoinBtnAction() {
        if !isHiddenCoin {
            hiddenCoinBtn.photoImageView.image = UIImage(named: "assetSelect")
        }else {
            hiddenCoinBtn.photoImageView.image = UIImage(named: "assetUnSelect")
        }
        isHiddenCoin = !isHiddenCoin
        tableView.reloadData()
    }
    deinit {
         self.viewModel?.removeObserver(self, forKeyPath: "refreshBool", context: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.Exchange.assetDidChange, object: nil)
    }
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
